<?php
define('LEGAL_OPER', true);
require('../../includes/admin-init.php');
require(ROOT_PATH . '/class/utils/FileUtil.class.php');
require(ROOT_PATH . '/class/utils/ValidateUtil.class.php');
//列表页
if($method == 'list'){
	$db = new DB();
	$templateTable = new BaseDao($db->getDb(), 'cms_template','tp_id');
	$templates = $templateTable->getAll('is_delete=?', array(0));
	$smarty->assign("templates",$templates);
	$smarty->display("cms/template_list.htm");
	exit;
}
//添加页
if($method == 'addui'){
	$smarty->display("cms/template_add.htm");
	exit;
}

//添加操作
if($method == 'add'){
	$name = $_POST['name'];
	$filename = $_POST['filename'];
	$type = (isset($_POST['type']) && $_POST['type']=='1')?1:2;
	if(isNotEmpty($name) && isLetterDigital($filename,1,20) && is_uploaded_file($_FILES['tpfile']['tmp_name'])){
		if(filesize($_FILES['tpfile']['tmp_name']) > 1000000){
			//文件过大
			$url = '/sys-admin/action/cms/template.php?met=addsuccess&code=4';
			to_redirect($url);
		}else{
			$filetype = $_FILES['tpfile']['type'];
			$typeCode = FileUtil::getTypeCode($_FILES['tpfile']['tmp_name']);
			
			if($filetype === 'text/html' && ($typeCode === 6033 || $typeCode === 60100)){
				$db = new DB();
				$templateTable = new BaseDao($db->getDb(), 'cms_template','tp_id');
				$db_tp = $templateTable->getOne('file_name=?', array(trim($filename)));
				if(isset($db_tp) && count($db_tp) > 0){
					//文件名已被占用
					$url = '/sys-admin/action/cms/template.php?met=addsuccess&code=2';
					to_redirect($url);
				}else{
					$db->beginTransaction();
					$templateTable = new BaseDao($db->getDb(), 'cms_template','tp_id');
				    try{
				    	$dir = 'cms/self/'.rand(0,9).'/';
				    	FileUtil::mkdirs(ADMIN_PATH.'/template/'.$dir);
				    	$values = array();
				    	$values['tp_name'] = trim($name);
				    	$values['file_name'] = trim($filename);
				    	$values['tp_type'] = $type;
				    	$values['tp_path'] = $dir.trim($filename).'.htm';
				    	$templateTable->save($values);
				    	//保存文件
				    	copy($_FILES['tpfile']['tmp_name'],ADMIN_PATH.'/template/'.$values['tp_path']);
				    	FileUtil::delete($_FILES['tpfile']['tmp_name']);
				    	$db->commit();
				    	$url = '/sys-admin/action/cms/template.php?met=addsuccess&code=1';
				    	to_redirect($url);
				    }catch (Exception $e){
				    	$db->rollback();
				    	//添加失败
				    	$url = '/sys-admin/action/cms/template.php?met=addsuccess&code=0';
					    to_redirect($url);
				    }
				}
				$db->close();
			}else{
			   //文件格式错误
				$url = '/sys-admin/action/cms/template.php?met=addsuccess&code=3';
				to_redirect($url);
			}
	    }
	}else{
		//参数错误
		$url = '/sys-admin/action/cms/template.php?met=addsuccess&code=0';
		to_redirect($url);
	}
	exit;
}
if($method == 'addsuccess'){
	$arr = array(
			'0'=>'模板添加失败',
			'1'=>'模板添加成功',
			'2'=>'模板文件名已被占用',
			'3'=>'模板文件格式错误',
			'4'=>'模板文件不能超过1M'
	);
	$links[0]['text'] = '继续添加';
	$links[0]['href'] = '/sys-admin/action/cms/template.php?met=addui';
	$links[1]['text'] = '模板列表';
	$links[1]['href'] = '/sys-admin/action/cms/template.php?met=list';
	to_message($smarty, $arr[$_GET['code']],0,$links);
}

//删除
if($method == 'delete'){
	$id = to_int($_GET['id']);
	$db = new DB();
	$db->beginTransaction();
	$templateTable = new BaseDao($db->getDb(), 'cms_template','tp_id');
	$template = $templateTable->getOne("tp_id=? and is_delete=?", array($id,0));
	if(isset($template) && count($template)){
		try{
			$templateTable->update(array('is_delete'=>1,'file_name'=>'*'.time().rand(10,99)),"tp_id=? and is_delete=?", array($id,0));
			FileUtil::delete(ADMIN_PATH.'/template/'.$template['tp_path']);
			$db->commit();
			echo 1;
		}catch(Exception $e){
			$db->rollback();
			echo 0;
		}
	}else{
		echo 0;
	}
	$db->close();
	exit;
}


//修改页
if($method == 'editui'){
	$id = to_int($_GET['id']);
	$db= new DB();
	$templateTable = new BaseDao($db->getDb(), 'cms_template','tp_id');
	$template = $templateTable->getOne("tp_id=? and is_delete=?", array($id,0));
	$db->close();
	$smarty->assign("template",$template);
	$smarty->display("cms/template_edit.htm");
	exit;
}

//修改操作
if($method == 'edit'){
	$id = to_int($_POST['id']);
	$name = $_POST['name'];
	$type = (isset($_POST['type']) && $_POST['type']=='1')?1:2;
	if($id > 0 && isNotEmpty($name)){
		$db = new DB();
		$db->beginTransaction();
		$templateTable = new BaseDao($db->getDb(), 'cms_template','tp_id');
		try{
			$values = array();
			$values['tp_name'] = trim($name);
			$values['tp_type'] = $type;
			$templateTable->update($values, 'tp_id=? and is_delete=?', array($id,0));
			$db->commit();
			$url = '/sys-admin/action/cms/template.php?met=editsuccess&code=1';
			to_redirect($url);
		}catch (Exception $e){
			$db->rollback();
			$url = '/sys-admin/action/cms/template.php?met=editsuccess&code=0';
			to_redirect($url);
		}
		$db->close();
	}else{
		//参数错误
		$url = '/sys-admin/action/cms/template.php?met=editsuccess&code=0';
		to_redirect($url);
	}
	exit;
}

if($method == 'editsuccess'){
	$arr = array(
			'0'=>'模板修改失败',
			'1'=>'模板修改成功',
	);
	$links[0]['text'] = '模板列表';
	$links[0]['href'] = '/sys-admin/action/cms/template.php?met=list';
	to_message($smarty, $arr[$_GET['code']],0,$links);
}



 if($method == 'download'){
 	$id = to_int($_GET['id']);
 	if($id > 0){
 		$db = new DB();
 		$templateTable = new BaseDao($db->getDb(), 'cms_template','tp_id');
 		$template = $templateTable->getOne("tp_id=? and is_delete=?", array($id,0));
 		if(isset($template) && count($template)){
 			$path =ADMIN_PATH.'/template/'.$template['tp_path'];
 			if (!file_exists($path)){
 				echo '<script type="text/javascript">alert("模板文件丢失了,赶紧去修改吧");</script>';
 			}else{
 				$file = fopen($path,"r");
 				Header("Content-type: application/octet-stream");
 				Header("Accept-Ranges: bytes");
 				Header("Accept-Length: ".filesize($path));
 				Header("Content-Disposition: attachment; filename=".$template['file_name'].'.htm');
 				echo fread($file, filesize($path));
 				fclose($file);
 			}
 		}else{
 			echo '<script type="text/javascript">alert("模板下载失败");</script>';
 		}
 	}else{
 		echo '<script type="text/javascript">alert("模板下载失败");</script>';
 	}
 	exit;
}


//修改模板文件操作
if($method == 'edittemplatefile'){
	$filename = $_POST['filename'];
	$tpid = to_int($_POST['tpid']);
	if($tpid > 0 && isLetterDigital($filename,1,20) && is_uploaded_file($_FILES['tpfile']['tmp_name'])){
		if(filesize($_FILES['tpfile']['tmp_name']) > 1000000){
			//文件过大
			echo '{code:2}';
		}else{
			$filetype = $_FILES['tpfile']['type'];
			$typeCode = FileUtil::getTypeCode($_FILES['tpfile']['tmp_name']);
			if($filetype === 'text/html' && ($typeCode === 6033 || $typeCode === 60100)){
				$db = new DB();
				$templateTable = new BaseDao($db->getDb(), 'cms_template','tp_id');
				
				$templateDB = $templateTable->getOne('tp_id=? and is_delete=?', array($tpid,0));
				if(isset($templateDB) && count($templateDB) > 0 ){
					$db_tps = $templateTable->getOne('tp_id <> ? and file_name=?', array($tpid,trim($filename)));
					if(isset($db_tps) && count($db_tps) > 0){
						//文件名已被占用
						echo '{code:3}';
					}else{
						$db->beginTransaction();
						$templateTable = new BaseDao($db->getDb(), 'cms_template','tp_id');
						try{
							$dir = 'cms/self/'.rand(0,9).'/';
							FileUtil::mkdirs(ADMIN_PATH.'/template/'.$dir);
							$values = array();
							$values['file_name'] = trim($filename);
							$values['tp_path'] = $dir.trim($filename).'.htm';
							$templateTable->update($values,'tp_id=? and is_delete=?', array($tpid,0));
							//删除原模板文件
							FileUtil::delete(ADMIN_PATH.'/template/'.$templateDB['tp_path']);
							//保存文件
							copy($_FILES['tpfile']['tmp_name'],ADMIN_PATH.'/template/'.$values['tp_path']);
							FileUtil::delete($_FILES['tpfile']['tmp_name']);
							$db->commit();
							echo '{code:1,name:\''.trim($filename).'\',path:\''.$values['tp_path'].'\'}';
						}catch (Exception $e){
							$db->rollback();
							//添加失败
							echo '{code:0}';
						}
					}
				}else{
					//模板不存在
					echo '{code:0}';
				}
				$db->close();
			}else{
				//文件格式错误
				echo '{code:4}';
			}
		}
	}else{
		//参数错误
		echo '{code:0}';
	}
	exit;
}


